package foxmob.mooc;

import org.apache.commons.io.IOUtils;
import spark.Request;

import javax.servlet.MultipartConfigElement;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/*
import javax.xml.parsers.SAXParser;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
*/
/**
 * Created by liyusen on 2017/3/29.
 */
public  class Utils {

    public static String[] getMultipart(String[] names,Request req){
        req.attribute("org.eclipse.jetty.multipartConfig",
                new MultipartConfigElement(AppCfg.sUploadTmpPath));
        String[] values = new String[names.length];
        for(int i=0;i<names.length;i++){
            try (InputStream is = req.raw().getPart(names[i]).getInputStream()) {
                values[i] = IOUtils.toString(is, "UTF-8");
                System.out.println(String.format("%s:%s",names[i],values[i]));
            }catch(Exception e){
                e.printStackTrace();
                return new String[]{"0"};
            }
        }
        return values;

    }
    public static boolean storeFile(Request req, String name, String filepath){
        req.attribute("org.eclipse.jetty.multipartConfig",
                new MultipartConfigElement(AppCfg.sUploadTmpPath));

        try (InputStream is = req.raw().getPart(name).getInputStream()) {
            File f = new File(AppCfg.sFileStorePath+filepath);
            if(!f.exists() && f.createNewFile()){
                OutputStream os = new FileOutputStream(f);
                return  IOUtils.copy(is,os)>0;

            }else{
                return false;
            }

        }catch(Exception e){
            e.printStackTrace();

        }

        return false;
    }


}
